package com.worldtolearn.offer.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.worldtolearn.offer.entity.Offer;

@Repository
public class OfferDao extends HibernateDaoSupport implements IOfferDao, Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	public void init(SessionFactory factory) {
	    setSessionFactory(factory);
	}

	@Override
	public void createOffer(Offer offer) {
		getHibernateTemplate().save(offer.getRate());
		getHibernateTemplate().save(offer.getSupplierOffer());
		getHibernateTemplate().save(offer);
	}

	@Override
	public void deleteOffer(Offer offer) {
		getHibernateTemplate().delete(offer);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getAllOffers() {
		return getHibernateTemplate().find("from Offer");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getOfferByLabelOffer(String labelOffer) {
		return getHibernateTemplate().findByNamedParam("select o from Offer o where o.labelOffer like :label", "label", labelOffer);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getOfferByActivity(String activity) {
		return getHibernateTemplate().findByNamedParam("select o from Offer o "
				+ "where o.supplierOffer.activity.labelActivity like :activity", "activity", activity);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getOfferByCountry(String country) {
		return getHibernateTemplate().findByNamedParam("select o from Offer o "
				+ "where o.supplierOffer.adress.country like :country", "country", country);
	}
		
	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getOfferBySearchCriterion(String[] param) {
		String[] criteria = {"activity","country"};		
		return getHibernateTemplate().findByNamedParam("select o from Offer o "
				+ "where o.supplierOffer.activity.labelActivity like :activity "
				+ "and o.supplierOffer.adress.country like :country",criteria, param);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Offer> getOfferById(int id) {
		return getHibernateTemplate().findByNamedParam("select o from Offer o where o.idOffer like :id", "id", id);
	}
}
